package com.hjy.hjyojbackendjudgeservice.judge;

import cn.hutool.json.JSONUtil;
import com.hjy.hjyojbackendcommon.common.ErrorCode;
import com.hjy.hjyojbackendcommon.exception.BusinessException;
import com.hjy.hjyojbackendjudgeservice.judge.codesandbox.CodeSandBox;
import com.hjy.hjyojbackendjudgeservice.judge.codesandbox.CodeSandboxFactory;
import com.hjy.hjyojbackendjudgeservice.judge.codesandbox.CodeSandboxProxy;
import com.hjy.hjyojbackendjudgeservice.model.codesandbox.ExeccuteCodeRequest;
import com.hjy.hjyojbackendjudgeservice.model.codesandbox.ExeccuteCodeResponse;
import com.hjy.hjyojbackendjudgeservice.model.codesandbox.JudgeInfo;
import com.hjy.hjyojbackendjudgeservice.model.dto.question.JudgeCase;
import com.hjy.hjyojbackendjudgeservice.model.entity.Question;
import com.hjy.hjyojbackendjudgeservice.model.entity.QuestionSubmit;
import com.hjy.hjyojbackendjudgeservice.model.enums.QuestionSubmitStatusEnum;
import com.hjy.hjyojbackendjudgeservice.judge.strategy.JudgeContext;
import com.hjy.hjyojbackendserviceclient.service.JudgeServiceClient;
import com.hjy.hjyojbackendserviceclient.service.QuestionFerignClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class JudgeServiceImpl implements JudgeService {
    @Resource
    private QuestionFerignClient questionService;
    @Resource
    private JudgeManage judgeManage;
    @Value("${codesandbox.type:example}")
    private String type;

    @Override
    public QuestionSubmit dojudge(Long questionSubmitId) {
        //1.获取前端提交的questionSubmitId
//        QuestionSubmit questionSubmit = questionSubmitService.getById(questionSubmitId);
        QuestionSubmit questionSubmit = questionService.getQuestionSubmitById(questionSubmitId);

        if (questionSubmit == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "提交信息不存在");
        }
        //2.根据QuestionSubmit中的questionid获取对应的题目信息
        Long questionId = questionSubmit.getQuestionId();
//        Question question = questionService.getById(questionId);
        Question question= questionService.getQuestionById(questionId);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "题目不存在");
        }
        if (!questionSubmit.getStatus().equals(QuestionSubmitStatusEnum.WAITING.getValue())) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "题目正在判题");
        }
        //3.更新QuestionSubmit中的判题状态。 通过传入的questionSubmitId来更新判题状态。
        QuestionSubmit questionSubmitUpdate = new QuestionSubmit();
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.RUNNING.getValue());
//        boolean questionSubmitUpdateResult = questionSubmitService.updateById(questionSubmitUpdate);
        boolean questionSubmitUpdateResult = questionService.updateQuestionSubmitById(questionSubmitUpdate);
        if (!questionSubmitUpdateResult) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "题目状态更新错误");
        }
        //4.调用沙箱，获取执行结果
        CodeSandBox codeSandBox = CodeSandboxFactory.cdeSandboxFactory(type);//静态工厂模式
        codeSandBox = new CodeSandboxProxy(codeSandBox);//代理模式
        String code = questionSubmit.getCode();
        String language = questionSubmit.getLanguage();
        List<JudgeCase> judgeCaseList = JSONUtil.toList(question.getJudgeCase(), JudgeCase.class);
        List<String> inputList = judgeCaseList.stream().map(JudgeCase::getInput).collect(Collectors.toList());

        ExeccuteCodeRequest execcuteCodeRequest = ExeccuteCodeRequest.builder().code(code).inputList(inputList).language(language).build();
        ExeccuteCodeResponse execcuteCodeResponse = codeSandBox.execcuteCode(execcuteCodeRequest);
        List<String> outputList = execcuteCodeResponse.getOutputList();

        JudgeContext judgeContext = new JudgeContext();
        judgeContext.setJudgeInfo(execcuteCodeResponse.getJudgeInfo());
        judgeContext.setOutputList(outputList);
        judgeContext.setInputList(inputList);
        judgeContext.setJudgeCaseList(judgeCaseList);
        judgeContext.setQuestion(question);
        judgeContext.setQuestionSubmit(questionSubmit);
        //根据策略模式选择创建什么样判题信息
//        DefaultJudgeStrategy defaultJudgeStrategy = new DefaultJudgeStrategy();
//        JudgeInfo judgeInfo = defaultJudgeStrategy.doJudge(judgeContext);
        JudgeInfo judgeInfo = judgeManage.doJudge(judgeContext);
        //修改数据库中的判题结果
        questionSubmitUpdate = new QuestionSubmit();
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.SUCCEED.getValue());
        questionSubmitUpdate.setJudgeInfo(JSONUtil.toJsonStr(judgeInfo));
//        questionSubmitUpdateResult = questionSubmitService.updateById(questionSubmitUpdate);
        questionSubmitUpdateResult= questionService.updateQuestionSubmitById(questionSubmitUpdate);
        if (!questionSubmitUpdateResult) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "题目状态更新错误");
        }
//        QuestionSubmit questionSubmitResult = questionSubmitService.getById(questionSubmitId);
        QuestionSubmit questionSubmitResult =questionService.getQuestionSubmitById(questionSubmitId);
        return questionSubmitResult;
    }
}
//- 可能还有其他的异常情况